<template>
  <div class="dispatch-page">
    <div class="header-bar">
      <h1 class="page-title">警力调度</h1>
      <div class="controls">
        <button class="btn btn-secondary" @click="refreshPoliceForce">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"></polyline><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path></svg>
          <span>刷新警力</span>
        </button>
      </div>
    </div>

    <div class="main-layout">
      <!-- 左栏：可用警力 -->
      <aside class="left-panel">
        <div class="panel-header">可用警力</div>
        <div class="officer-list">
          <div
            v-for="officer in availableOfficers"
            :key="officer.id"
            class="officer-card"
            :class="{ selected: isSelected(officer) }"
            @click="toggleOfficerSelection(officer)">
            <div class="officer-info">
              <span class="officer-name">{{ officer.name }}</span>
              <span class="officer-department">{{ officer.department }}</span>
            </div>
            <div class="officer-status" :class="`status-${officer.statusDescription}`">{{ officer.statusDescription }}</div>
            <div class="officer-skills">技能: {{ officer.skills }}</div>
          </div>
        </div>
      </aside>

      <!-- 中栏：地图 -->
      <div class="center-panel">
        <MapContainerForDispatch
          ref="mapRef"
          :officers="availableOfficers"
          :incidents="[targetIncident].filter(Boolean).filter(incident => incident.lng && incident.lat)"
        />
      </div>

      <!-- 右栏：调度信息 -->
      <aside class="right-panel" ref="rightPanelRef" :class="{ 'highlight-flash': highlightPanel }">
        <div class="panel-header">调度信息</div>
        <div v-if="targetIncident" class="dispatch-info-card"> <!-- 添加条件渲染 -->
          <div class="info-item">
            <span class="label">事件类型:</span>
            <span class="value">{{ targetIncident.incidentType || '未指定' }}</span> <!-- 直接访问属性 -->
          </div>
          <div class="info-item">
            <span class="label">事件位置:</span>
            <span class="value">{{ targetIncident.location || getLocationDisplay(targetIncident) || '未指定' }}</span>
          </div>
          <div class="info-item selected-officers">
            <span class="label">已选警员:</span>
            <span class="value" v-if="selectedOfficers.length === 0">无</span>
            <div v-else class="tags">
              <span v-for="officer in selectedOfficers" :key="officer.id" class="tag">
                {{ officer.name }}
                <span class="remove-tag" @click.stop="removeSelectedOfficer(officer)">×</span>
              </span>
            </div>
          </div>
        </div>
        <div v-else class="dispatch-info-card placeholder-card"> <!-- 加载中占位 -->
          <div class="info-item">
            <span class="label">事件类型:</span>
            <span class="value">加载中...</span>
          </div>
          <div class="info-item">
            <span class="label">事件位置:</span>
            <span class="value">加载中...</span>
          </div>
        </div>
        <div class="dispatch-actions">
          <button class="btn btn-ai" @click="getAiSuggestion">AI智能调度建议</button>
          <button class="btn btn-execute" @click="executeDispatch">执行调度</button>
        </div>
      </aside>
    </div>

    <AiSuggestionModal
      v-if="isAiModalOpen"
      :suggestion="aiSuggestion"
      @close="isAiModalOpen = false"
      @confirm="applyAiSuggestion"
    />
    <InfoModal
      v-if="isInfoModalOpen"
      :type="infoModalContent.type"
      :title="infoModalContent.title"
      :message="infoModalContent.message"
      @close="isInfoModalOpen = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, nextTick } from 'vue';
import { useRoute } from 'vue-router';
import MapContainerForDispatch from "@/views/dashboard/MapContainerForDispatch.vue";
import AiSuggestionModal from './AiSuggestionModal.vue';
import InfoModal from '@/components/InfoModal.vue';
import api from '@/utils/axios';
import axios from 'axios';

const API_BASE_URL = 'http://localhost:8080/api/auth';
const AMAP_API_KEY = 'e67f0e9520643f148baa0e9747a27038'; // 替换为你的高德地图 API Key
const CHAT_API_URL = 'http://localhost:8080/chat'; // 后端聊天接口地址

const route = useRoute();
const mapRef = ref<any>(null);
const rightPanelRef = ref<HTMLElement | null>(null);
const highlightPanel = ref(false);

// 状态管理
const isLoading = ref(true); // 增加加载状态
const errorMessage = ref('');

// 从后端获取所有警员数据
const allOfficers = ref<any[]>([]);
const targetIncident = ref<any>(null);
const selectedOfficers = ref<any[]>([]);

// 地图中心位置
const MAP_CENTER = { lng: 84.87, lat: 45.59 };
// 地图范围（经纬度差值）
const MAP_RANGE = { lng: 0.2, lat: 0.2 };

// 生成随机位置
const generateRandomPosition = () => {
  const lng = MAP_CENTER.lng + (Math.random() - 0.5) * MAP_RANGE.lng;
  const lat = MAP_CENTER.lat + (Math.random() - 0.5) * MAP_RANGE.lat;
  return { lng, lat };
};

// 从后端获取警员列表
const fetchOfficers = async () => {
  isLoading.value = true;
  errorMessage.value = '';
  try {
    const response = await api.get(`${API_BASE_URL}/officers`);
    allOfficers.value = response.data.data.map((officer: any) => {
      const position = officer.longitude && officer.latitude
        ? { lng: officer.longitude, lat: officer.latitude }
        : generateRandomPosition();
      return {
        id: officer.officerId,
        name: officer.name,
        department: officer.department,
        statusDescription: officer.statusDescription,
        skills: officer.skills,
        ...position
      };
    });
  } catch (error) {
    console.error('获取警员列表失败:', error);
    // 处理不同类型的错误
    if (error.response) {
      if (error.response.status === 401) {
        errorMessage.value = '认证失败，请重新登录';
      } else if (error.response.status === 403) {
        errorMessage.value = '权限不足，无法获取警员信息';
      } else if (error.response.status === 404) {
        errorMessage.value = '未找到警员数据';
      } else {
        errorMessage.value = `获取失败: ${error.response.status} ${error.response.statusText}`;
      }
    } else if (error.request) {
      errorMessage.value = '无法连接到服务器，请检查网络连接';
    } else {
      errorMessage.value = `发生错误: ${error.message}`;
    }
  } finally {
    isLoading.value = false;
  }
};

// 可用警力是状态为在岗的警员
const availableOfficers = computed(() => {
  return allOfficers.value.filter(officer => officer.statusDescription === '在岗');
});

// 根据经纬度获取地址信息
const getAddressByCoordinates = async (lng: number, lat: number) => {
  try {
    const response = await axios.get(`https://restapi.amap.com/v3/geocode/regeo?key=${AMAP_API_KEY}&location=${lng},${lat}`);
    if (response.data.status === '1') {
      return response.data.regeocode.formatted_address;
    }
    return null;
  } catch (error) {
    console.error('获取地址信息失败:', error);
    return null;
  }
};

// 根据路由参数加载事件详情
const loadIncidentDetails = async (eventId: string | number | null) => {
  if (eventId) {
    isLoading.value = true;
    console.log("eventId:" + eventId)
    try {
      const response = await api.get(`${API_BASE_URL}/incidents/${eventId}`);
      // 确保事件数据包含经纬度信息
      if (response.data.coordinates && response.data.coordinates.length >= 2) {
        targetIncident.value = {
          ...response.data,
          lng: parseFloat(response.data.coordinates[0].toString()),
          lat: parseFloat(response.data.coordinates[1].toString())
        };

        // 根据经纬度获取地址信息
        const address = await getAddressByCoordinates(targetIncident.value.lng, targetIncident.value.lat);
        if (address) {
          targetIncident.value.location = address;
        } else {
          // 如果获取地址失败，随机生成一个地名
          const commonLocations = ['平安大街', '幸福路', '光明社区', '和谐广场', '希望小区'];
          const randomIndex = Math.floor(Math.random() * commonLocations.length);
          targetIncident.value.location = commonLocations[randomIndex];
        }
      } else {
        console.error('事件数据缺少经纬度信息:', response.data);
        targetIncident.value = null;
        infoModalContent.value = { type: 'error', title: '数据错误', message: '事件数据缺少经纬度信息，请检查数据。' };
        isInfoModalOpen.value = true;
      }
      console.log("事件详情:", targetIncident.value)
      selectedOfficers.value = [];
      nextTick(() => {
        rightPanelRef.value?.scrollIntoView({ behavior: 'smooth', block: 'center' });
        highlightPanel.value = true;
        setTimeout(() => {
          highlightPanel.value = false;
        }, 5000);
      });
    } catch (error) {
      console.error('获取事件详情失败:', error);
      infoModalContent.value = { type: 'error', title: '获取事件失败', message: '无法加载事件详情，请稍后重试。' };
      isInfoModalOpen.value = true;
    } finally {
      isLoading.value = false;
    }
  } else {
    targetIncident.value = null;
    isLoading.value = false;
  }
};

// 监听路由参数变化
watch(
  () => route.query.eventId,
  async (newEventId) => {
    console.log("进入loadIncidentDetails")
    await loadIncidentDetails(newEventId);
  },
  { immediate: true }
);

// 其他函数
const isSelected = (officer: any) => selectedOfficers.value.some(o => o.id === officer.id);
const toggleOfficerSelection = (officer: any) => {
  const index = selectedOfficers.value.findIndex(o => o.id === officer.id);
  if (index > -1) {
    selectedOfficers.value.splice(index, 1);
  } else {
    selectedOfficers.value.push(officer);
  }
  mapRef.value?.panTo(officer.lng, officer.lat);
};
const removeSelectedOfficer = (officer: any) => {
  selectedOfficers.value = selectedOfficers.value.filter(o => o.id !== officer.id);
};

// 获取位置显示文本
const getLocationDisplay = (incident: any) => {
  if (incident?.coordinates && incident.coordinates.length >= 2) {
    // 格式化经纬度，保留6位小数
    const lng = parseFloat(incident.coordinates[0].toString()).toFixed(6);
    const lat = parseFloat(incident.coordinates[1].toString()).toFixed(6);
    return `经度: ${lng}, 纬度: ${lat}`;
  }
  return '位置未知';
};

// 弹窗控制逻辑
const isAiModalOpen = ref(false);
const aiSuggestion = ref({ officerName: '', department: '', reason: '' });
const isInfoModalOpen = ref(false);
const infoModalContent = ref({ type: 'success' as 'success' | 'error', title: '', message: '' });

const refreshPoliceForce = async () => {
  await fetchOfficers();
  infoModalContent.value = { type: 'success', title: '刷新成功', message: '可用警力信息已更新。' };
  isInfoModalOpen.value = true;
};

// 优化后的AI建议获取函数
const getAiSuggestion = async () => {
  if (!targetIncident.value) {
    infoModalContent.value = { type: 'error', title: '操作失败', message: '请先关联一个事件才能获取AI建议。' };
    isInfoModalOpen.value = true;
    return;
  }

  // 组合事件信息和警员信息
  const message = {
    incidentType: targetIncident.value.incidentType,
    location: targetIncident.value.location,
    officers: availableOfficers.value
  };

  try {
    const response = await api.post(CHAT_API_URL, message,{timeout:30000});
    const suggestionText = response.data;
    console.log("AI响应文本:", suggestionText);

    let officerName = '未知';
    let department = '未知';
    let reason = '无法解析建议文本';

    // 针对当前AI响应格式的专用解析逻辑
    // 格式: "AI建议指派警员: 张伟 (治安科)。[推荐理由] 推荐理由内容"
    const mainMatch = suggestionText.match(/AI建议指派警员:\s*([^（\(]+)\s*[（\(]([^）\)]+)[）\)]\s*。\s*\[推荐理由\]\s*(.*)/);

    if (mainMatch && mainMatch.length === 4) {
      // 成功匹配完整格式
      officerName = mainMatch[1].trim();
      department = mainMatch[2].trim();
      reason = mainMatch[3].trim();
    } else {
      // 尝试匹配不带[推荐理由]标记的格式
      const fallbackMatch = suggestionText.match(/AI建议指派警员:\s*([^（\(]+)\s*[（\(]([^）\)]+)[）\)]\s*。\s*(.*)/);
      if (fallbackMatch && fallbackMatch.length === 4) {
        officerName = fallbackMatch[1].trim();
        department = fallbackMatch[2].trim();
        reason = fallbackMatch[3].trim();
      } else {
        // 尝试更宽松的匹配
        const looseMatch = suggestionText.match(/AI建议指派警员[:：]\s*([^（\(]+)\s*[（\(]([^）\)]+)[）\)]\s*[。，]([\s\S]*)/);
        if (looseMatch && looseMatch.length === 4) {
          officerName = looseMatch[1].trim();
          department = looseMatch[2].trim();
          reason = looseMatch[3].trim();
        } else {
          // 尝试提取姓名和部门
          const nameDeptMatch = suggestionText.match(/([^（\(]+)\s*[（\(]([^）\)]+)[）\)]/);
          if (nameDeptMatch && nameDeptMatch.length === 3) {
            officerName = nameDeptMatch[1].trim();
            department = nameDeptMatch[2].trim();
            reason = suggestionText.replace(nameDeptMatch[0], '').trim();
          }
        }
      }
    }

    // 尝试从可用警员列表中查找部门（如果解析失败）
    if (department === '未知') {
      const officer = availableOfficers.value.find(o => o.name === officerName);
      if (officer) {
        department = officer.department;
      }
    }

    aiSuggestion.value = {
      officerName,
      department,
      reason
    };

    isAiModalOpen.value = true;
  } catch (error) {
    console.error('获取AI建议失败:', error);
    infoModalContent.value = { type: 'error', title: '获取AI建议失败', message: '请稍后重试。' };
    isInfoModalOpen.value = true;
  }
};

const applyAiSuggestion = () => {
  const recommendedOfficer = availableOfficers.value.find(o => o.name === aiSuggestion.value.officerName);
  if (recommendedOfficer && !isSelected(recommendedOfficer)) {
    selectedOfficers.value.push(recommendedOfficer);
  }
  isAiModalOpen.value = false;
};

const executeDispatch = async () => {
  if (!targetIncident.value || selectedOfficers.value.length === 0) {
    infoModalContent.value = { type: 'error', title: '调度失败', message: '请确保已关联事件并至少选择一名警员。' };
    isInfoModalOpen.value = true;
    return;
  }

  try {
    const incidentId = targetIncident.value.incidentId;
    const officerIds = selectedOfficers.value.map(officer => officer.id);
    await api.post(`${API_BASE_URL}/incidents/${incidentId}/officers`, officerIds);

    const officerNames = selectedOfficers.value.map(o => o.name).join('、');
    infoModalContent.value = {
      type: 'success', title: '调度成功',
      message: `已成功指派 ${officerNames} 前往处理"${targetIncident.value.incidentType}"事件。`
    };
    isInfoModalOpen.value = true;
    selectedOfficers.value = [];
  } catch (error) {
    console.error('调度失败:', error);
    infoModalContent.value = { type: 'error', title: '调度失败', message: '无法执行调度，请稍后重试。' };
    isInfoModalOpen.value = true;
  }
};

// 组件挂载时获取警员数据并确保地图加载
onMounted(async () => {
  await fetchOfficers();
  // 确保警员数据加载完成后地图能正确显示
  await nextTick();
});
</script>

<style scoped>
@import "@/assets/styles/views/dashboard/Dispatch.css";

/* 加载中占位样式 */
.placeholder-card {
  opacity: 0.5;
  pointer-events: none;
}
</style>
